/***************************************************************************
 * Copyright 2012 TXT e-solutions SpA
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * This work was performed within the IoT_at_Work Project
 * and partially funded by the European Commission's
 * 7th Framework Programme under the research area ICT-2009.1.3
 * Internet of Things and enterprise environments.
 *
 * Authors:
 *      Salvatore Piccione (TXT e-solutions SpA)
 *
 * Contributors:
 *        Domenico Rotondi (TXT e-solutions SpA)
 **************************************************************************/
package it.txt.ens.authorisationService.gui.standalone;

import it.txt.access.capability.pdp.client.PDPClientConfiguration;
import it.txt.access.capability.pdp.client.PDPClientFactory;
import it.txt.access.capability.pdp.client.PDPClientFactoryImpl;
import it.txt.ens.authorisationService.util.AccessRequestListener;
import it.txt.ens.authorisationService.util.ConfigurationParser;
import it.txt.ens.core.ENSAuthzServiceConnectionParameters;
import it.txt.ens.core.KeystoreParameters;
import it.txt.ens.core.X509CertificateRetrievalParameters;
import it.txt.ens.core.factory.ENSAuthzServiceConnectionParametersFactory;
import it.txt.ens.core.factory.ENSResourceFactory;
import it.txt.ens.core.factory.KeystoreParametersFactory;
import it.txt.ens.core.factory.X509CertificateRetrievalParametersFactory;
import it.txt.ens.core.impl.BasicENSResource;
import it.txt.ens.core.util.parser.KeystoreParametersMapParser;
import it.txt.ens.core.util.parser.ParseException;
import it.txt.ens.core.util.parser.X509CertificateRetrievalParametersMapParser;
import it.txt.ens.namespace.NamespaceInquirerConfiguration;
import it.txt.ens.namespace.NamespaceInquirerFactory;
import it.txt.ens.namespace.NamespaceInquirerFactoryImpl;
import it.txt.ens.schema.factory.ENSRequestFactoryException;
import it.txt.ens.schema.factory.ENSResponseFactoryException;
import it.txt.ens.schema.request.factory.ENSAuthorisationRequestFactory;
import it.txt.ens.schema.request.factory.ENSAuthorisationRequestFactoryImpl;
import it.txt.ens.schema.response.factory.ENSAuthorisationResponseFactory;
import it.txt.ens.schema.response.factory.ENSAuthorisationResponseFactoryImpl;
import it.txt.rabbitmq.management.rest.factory.PermissionServiceFactory;
import it.txt.rabbitmq.management.rest.factory.PermissioneServiceFactoryImpl;
import it.txt.rabbitmq.management.rest.factory.QueueServiceFactoryImpl;
import it.txt.rabbitmq.management.rest.factory.UserServiceFactory;
import it.txt.rabbitmq.management.rest.factory.UserServiceFactoryImpl;
import it.txt.rabbitmq.management.rest.services.QueueService;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.Properties;
import java.util.ServiceLoader;

/**
 * @author Salvatore Piccione (TXT e-solutions SpA - salvatore.piccione AT network.txtgroup.com)
 * 
 */
public class ENSAuthorisationServiceStarter {
    private static ENSAuthzServiceConnectionParameters ensAuthzServiceConnParams;

	public static void main(String[] args) {
//		if (args.length == 0) {
//			System.err.println("Please, indicate the path of the configuration file!");
//			return;
//		}
//		try {
//			ApplicationPropertiesRepository.initProperties(args[0]);
//		} catch (IOException e) {
//			System.err.println(e);
//			return;
//		}
		
		String configUrl = "D:/conf/ENSConfig.properties";
		
		File file = new File(configUrl);
		FileInputStream is;
		Properties myProps = null;
		try {
			is = new FileInputStream(file);
			myProps = new Properties();
			myProps.load(is);
			is.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
            e.printStackTrace();
            System.exit(1);
            return;
		}
		
        PDPClientFactory pdpClientFactory = new PDPClientFactoryImpl();
        PDPClientConfiguration pdpClientConfiguration = pdpClientFactory.createConfiguration(myProps);
        NamespaceInquirerFactory namespaceInquirerFactory = new NamespaceInquirerFactoryImpl();
        NamespaceInquirerConfiguration namespaceInquirerConfig = namespaceInquirerFactory.createConfiguration(myProps);
        UserServiceFactory userMgmtSF = new UserServiceFactoryImpl();
        PermissionServiceFactory permissionMgmtSF = new PermissioneServiceFactoryImpl();
        ENSAuthorisationResponseFactory responseFactory;
        try {
            responseFactory = ENSAuthorisationResponseFactoryImpl.getInstance(
                    myProps.getProperty(ENSAuthorisationResponseFactory.SCHEMAS_DIRECTORY_PROP_KEY));
        } catch (ENSResponseFactoryException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.exit(1);
            return;
        }
        ENSAuthorisationRequestFactory requestFactory;
        try {
            requestFactory = ENSAuthorisationRequestFactoryImpl.getInstance(
                    myProps.getProperty(ENSAuthorisationResponseFactory.SCHEMAS_DIRECTORY_PROP_KEY));
        } catch (ENSRequestFactoryException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.exit(1);
            return;
        }
        
        KeystoreParametersFactory keystoreParamsFactory = loadService(KeystoreParametersFactory.class);
        KeystoreParameters keystoreParams;
        if (keystoreParamsFactory == null) {
            System.exit(1);
            return;
        } else {
            try {
                keystoreParams = KeystoreParametersMapParser.parse(keystoreParamsFactory, myProps);
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                System.exit(1);
                return;
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                System.exit(1);
                return;
            }
        }

        X509CertificateRetrievalParametersFactory certParamsFactory = loadService(X509CertificateRetrievalParametersFactory.class);
        X509CertificateRetrievalParameters certParams;
        if (certParamsFactory ==  null) {
            System.exit(1);
            return;
        } else
            try {
                certParams = X509CertificateRetrievalParametersMapParser.parse(certParamsFactory, myProps);
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                System.exit(1);
                return;
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                System.exit(1);
                return;
            }
        
        ENSAuthzServiceConnectionParametersFactory connParamsFactory = loadService(ENSAuthzServiceConnectionParametersFactory.class);
        if (connParamsFactory == null) {
            System.exit(1);
            return;
        }
        ConfigurationParser configParser = new ConfigurationParser(myProps, connParamsFactory);
        
        //FIXME GET THEM FROM THE ARGS
        int threadPoolSize = 5;
        

        QueueService queueMgmt = new QueueServiceFactoryImpl().create(
                ensAuthzServiceConnParams.getBrokerHost(), 
                ensAuthzServiceConnParams.getBrokerPort(),
                ensAuthzServiceConnParams.getSubjectID(),
                ensAuthzServiceConnParams.getAccessToken());
        ENSResourceFactory resourceFactory = new BasicENSResource.BasicENSResourceFactory();
        AccessRequestListener runListener = new AccessRequestListener(ensAuthzServiceConnParams, 
                pdpClientFactory, pdpClientConfiguration, namespaceInquirerFactory,
                namespaceInquirerConfig, userMgmtSF, permissionMgmtSF, queueMgmt,
                responseFactory, requestFactory, keystoreParams, certParams,
                resourceFactory , configParser.getVirtualHostMap(),configParser.getNamespaceMap(), 
                configParser.getBrokerMap(), threadPoolSize);

		//Application start up
		ENSAuthorisationServiceGUI a = new ENSAuthorisationServiceGUI(runListener);
		a.setVisible(true);

	}
	
	private static <S> S loadService (Class<S> serviceClass) {
	    ServiceLoader<S> keystoreParamsFactorySL = ServiceLoader.load(serviceClass);
        Iterator<S> keystoreParamsFactoryI = keystoreParamsFactorySL.iterator();
        if (keystoreParamsFactoryI.hasNext()) {
            return keystoreParamsFactoryI.next();
        } else {
            System.err.println("No instance of " + serviceClass.getName() + " has been found");
            return null;
        }
	}
    
}
